<template>
  <el-radio-group :model-value="modelValue" @update:modelValue="updateValue">
    <el-radio-button v-for="item in data" :key="item.id" :label="item.id">
      {{ item.title }}
    </el-radio-button>
  </el-radio-group>
</template>

<script setup>
  import { ref, onMounted } from 'vue';
  import { EleMessage } from 'ele-admin-plus/es';
  import { pageMyCompanyArea } from '@/api/company';

  const emit = defineEmits(['update:modelValue']);

  const props = defineProps({
    all: {
      type: Boolean,
      default: true
    },
    other: {
      type: Boolean,
      default: false
    },
    choose: {
      type: Boolean,
      default: true
    },
    /** 选中的区域ID */
    modelValue: [Number, String] // 允许数字或字符串
  });

  /** 站点数据 */
  const data = ref([]);

  /** 更新选中数据 */
  const updateValue = (value) => {
    emit('update:modelValue', value);
  };

  /** 获取站点数据并设置默认值 */
  const loadAreas = async () => {
    try {
      const res = await pageMyCompanyArea({
        all: props.all ? 1 : 0,
        other: props.other ? 1 : 0
      });
      data.value = res.list || [];

      // 如果有数据，并且 `modelValue` 为空，则默认选中第一个 id
      if (data.value.length > 0 && !props.modelValue && props.choose) {
        emit('update:modelValue', data.value[0].id);
      }
    } catch (e) {
      EleMessage.error(e.message);
    }
  };

  onMounted(loadAreas);
</script>
